package cn.bugstack.gateway.session.defaults;

import cn.bugstack.gateway.session.Configuration;
import cn.bugstack.gateway.session.IGenericReferenceSessionFactory;
import cn.bugstack.gateway.session.SessionServer;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

@Slf4j
// 会话工厂（用来泛化调用，启动 sessionSever）
public class GenericReferenceSessionFactory implements IGenericReferenceSessionFactory {

    private final Configuration configuration;

    public GenericReferenceSessionFactory(Configuration configuration) {
        this.configuration = configuration;
    }

    // 工厂启动 SessionServer
    @Override
    public Future<Channel> openSession() throws ExecutionException, InterruptedException {
        SessionServer sessionServer = new SessionServer(configuration);
        // 线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
        // 得到执行结果，即 Channel
        Future<Channel> future = executor.submit(sessionServer);
        Channel channel = future.get();
        // 检查通道
        if (channel == null) {
            throw new RuntimeException("netty server channel is null");
        }
        while (!channel.isActive()) {
            log.info("waiting for netty server channel active...");
            Thread.sleep(500);
        }

        log.info("netty server channel active.{}", channel.localAddress());
        return future;
    }
}
